module wwnd ! weight window
    implicit none
    real(8), private, pointer, dimension(:) :: ww
    integer, private :: nm,ng
    integer, parameter :: NOEV=0, SPLT=1, TERM=2
    real(8), private, parameter :: rho = 4._8
contains

subroutine init_wwnd(nm_,ng_)
    integer, intent(in) :: nm_,ng_
    nm = nm_
    ng = ng_
    allocate(ww(nm))
end subroutine

! 1 group condense
subroutine update_ww(phi)
    real(8), pointer, intent(in), dimension(:,:) :: phi
    real(8) :: phimax
    integer :: i, g
    ww = 0 
    do g=1, ng
        do i=1,nm
            ww(i) = ww(i) + phi(i,g)
        end do
    enddo
    phimax =0
    do i=1, nm
        if (ww(i)>phimax) phimax = ww(i)
    end do
    ww = ww /phimax
end subroutine

function event_ww(w, m, g) result(ret)
    real(8), intent(inout) :: w
    integer, intent(in) :: m, g
    integer :: ret
    real(8):: wu, wb
    wu = ww(m)*rho
    wb = ww(m)/rho
    ret = NOEV
    if (w>wu) then
        ret = SPLT
        w = w / 2
    elseif(w<wb) then
        call RR(w, ret)
    endif
contains 
subroutine RR(w, ret)
    use rng
    real(8), intent(inout) :: w
    integer, intent(inout) :: ret
    if(getRN()<0.25_8) then
        w = w*4
        ret = NOEV
    else
        w = 0.
        ret = TERM
    endif
end subroutine

end function

end module
